package com.teaching.teachingsupport.service.impl.teacherserviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teaching.teachingsupport.common.pojo.dataobject.*;
import com.teaching.teachingsupport.common.utils.SecurityUtils;
import com.teaching.teachingsupport.mapper.TeacherMapper;
import com.teaching.teachingsupport.mapper.studentviewmapper.CourseMapper;
import com.teaching.teachingsupport.mapper.studentviewmapper.SemesterMapper;
import com.teaching.teachingsupport.mapper.teacherviewmapper.TeachingClassMapper;
import com.teaching.teachingsupport.mapper.teacherviewmapper.TeacherCourseMapper;
import com.teaching.teachingsupport.service.service2.teacherservice.TeachingClassService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class TeachingClassServiceImpl implements TeachingClassService {

    private final SecurityUtils securityUtils;
    private final TeacherMapper teacherMapper;
    private final TeachingClassMapper teachingClassMapper;
    private final CourseMapper courseMapper;
    private final SemesterMapper semesterMapper;
    private final TeacherCourseMapper teacherCourseMapper;

    @Override
    public Page<TeachingClass> getTeachingClasses(String username, String password, Integer page, Integer size) {
        // 1. 验证用户
        User user = securityUtils.validateUser(username, password);
        if (user == null) {
            return new Page<>();
        }

        return getTeachingClassesByUserId(user.getUserId(), page, size, null, null, null, null);
    }

    @Override
    public List<TeachingClass> getTeachingClassByUsername(String username, String password) {
        // 验证用户名和密码
        User user = securityUtils.validateUser(username, password);
        if (user == null) {
            return List.of();
        }

        return getTeachingClassByUserId(user.getUserId());
    }

    private List<TeachingClass> getTeachingClassByUserId(Long userId) {
        // 1. 获取教师信息
        Teacher teacher = teacherMapper.selectOne(
            new LambdaQueryWrapper<Teacher>()
                .eq(Teacher::getUserId, userId)
        );
        if (teacher == null) {
            return List.of();
        }

        // 2. 查询教学班级
        return teachingClassMapper.selectList(
            new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTeacherId, teacher.getUserId())
                .orderByDesc(TeachingClass::getSemesterId)
        );
    }

    @Override
    public Page<TeachingClass> getTeachingClassesByUserId(Long userId, Integer page, Integer size,
            String grade, String courseStatus, String studentStatus, String courseName) {
        // 1. 获取教师信息
        Teacher teacher = teacherMapper.selectOne(
                new LambdaQueryWrapper<Teacher>()
                .eq(Teacher::getUserId, userId)
        );
        if (teacher == null) {
            return new Page<>();
        }

        // 2. 构建基础查询条件
        LambdaQueryWrapper<TeachingClass> wrapper = new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTeacherId, teacher.getUserId());

        // 3. 动态添加搜索条件
        // 年级条件 - 支持精确匹配和模糊匹配
        if (StringUtils.hasText(grade)) {
            try {
                int gradeNum = Integer.parseInt(grade);
                wrapper.eq(TeachingClass::getGrade, gradeNum);
            } catch (NumberFormatException e) {
                wrapper.like(TeachingClass::getGrade, grade);
            }
        }

        // 课程状态条件
        if (StringUtils.hasText(courseStatus)) {
            wrapper.eq(TeachingClass::getStatus, courseStatus);
        }

        // 课程名称条件 - 使用左连接查询
        if (StringUtils.hasText(courseName)) {
            wrapper.exists("SELECT 1 FROM course c WHERE c.course_id = teaching_class.course_id AND c.course_name LIKE CONCAT('%',{0},'%')", courseName);
        }

        // 学生状态条件 - 如果需要
        if (StringUtils.hasText(studentStatus)) {
            wrapper.exists("EXISTS (SELECT 1 FROM student_course sc WHERE sc.course_id = teaching_class.course_id AND sc.status = {0})", studentStatus);
        }

        // 4. 排序
        wrapper.orderByDesc(TeachingClass::getSemesterId);

        // 5. 执行分页查询
        Page<TeachingClass> classPage = teachingClassMapper.selectPage(
                new Page<>(page, size),
                wrapper
        );

        // 6. 填充关联信息
        classPage.getRecords().forEach(teachingClass -> {
            // 获取课程信息
            Course course = courseMapper.selectById(teachingClass.getCourseId());
            if (course != null) {
                teachingClass.setCourseName(course.getCourseName());
            }
            
            // 获取学期信息
            Semester semester = semesterMapper.selectById(teachingClass.getSemesterId());
            if (semester != null) {
                teachingClass.setSemesterName(semester.getTermName());
            }

            // 获取上课时间和地点信息
            TeacherCourse teacherCourse = teacherCourseMapper.selectOne(
                new LambdaQueryWrapper<TeacherCourse>()
                    .eq(TeacherCourse::getCourseId, teachingClass.getCourseId())
                    .eq(TeacherCourse::getTeacherId, teachingClass.getTeacherId())
                    .eq(TeacherCourse::getSemesterId, teachingClass.getSemesterId())
            );
            if (teacherCourse != null) {
                teachingClass.setClassTime(teacherCourse.getClassTime());
                teachingClass.setClassLocation(teacherCourse.getClassLocation());
            }
        });

        return classPage;
    }

    @Override
    public Page<TeachingClass> getTeachingClassManagement(Long userId, Integer courseId, String grade, Integer page, Integer size) {
        // 1. 获取教师信息
        Teacher teacher = teacherMapper.selectOne(
            new LambdaQueryWrapper<Teacher>()
                .eq(Teacher::getUserId, userId)
        );
        if (teacher == null) {
            return new Page<>();
        }

        // 2. 构建查询条件
        LambdaQueryWrapper<TeachingClass> wrapper = new LambdaQueryWrapper<TeachingClass>()
            .eq(TeachingClass::getTeacherId, teacher.getUserId());
            
        // 如果指定了课程ID，添加课程过滤条件
        if (courseId != null) {
            wrapper.eq(TeachingClass::getCourseId, courseId);
        }
        
        // 如果指定了年级，使用grade字段进行精确匹配
        if (grade != null && !grade.isEmpty()) {
            try {
                int gradeYear = Integer.parseInt(grade);
                wrapper.eq(TeachingClass::getGrade, gradeYear);
            } catch (NumberFormatException e) {
                // 如果转换失败，说明输入的不是数字，则不添加年级过滤条件
            }
        }
        
        // 按学期降序排序
        wrapper.orderByDesc(TeachingClass::getSemesterId);

        // 3. 分页查询教学班
        Page<TeachingClass> classPage = teachingClassMapper.selectPage(
                new Page<>(page, size),
            wrapper
        );

        // 4. 填充课程和学期信息
        classPage.getRecords().forEach(teachingClass -> {
            // 获取课程信息
            Course course = courseMapper.selectById(teachingClass.getCourseId());
            if (course != null) {
                teachingClass.setCourseName(course.getCourseName());
            }
            
            // 获取学期信息
            Semester semester = semesterMapper.selectById(teachingClass.getSemesterId());
            if (semester != null) {
                teachingClass.setSemesterName(semester.getTermName());
            }

            // 获取上课时间和地点信息
            TeacherCourse teacherCourse = teacherCourseMapper.selectOne(
                new LambdaQueryWrapper<TeacherCourse>()
                    .eq(TeacherCourse::getCourseId, teachingClass.getCourseId())
                    .eq(TeacherCourse::getTeacherId, teachingClass.getTeacherId())
                    .eq(TeacherCourse::getSemesterId, teachingClass.getSemesterId())
            );
            if (teacherCourse != null) {
                teachingClass.setClassTime(teacherCourse.getClassTime());
                teachingClass.setClassLocation(teacherCourse.getClassLocation());
            }
        });

        return classPage;
    }
} 